<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add?questionnaire_id='+questionnaire_id)">新增问题</button>
				<button class="uni-button" type="default" size="mini" @click="delTable">批量删除</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" collection="opendb-vote-question" gettree :startwith="startwith"
			  :orderby="orderby" :getcount="true" page-data="replace"  :page-size="options.pageSize" :page-current="options.pageCurrent"
			  v-slot:default="{data,pagination,loading,error,options}" :options="options" manual>
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection"
				 @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">问题</uni-th>
						<uni-th align="center">选项</uni-th>
						<uni-th align="center">问题类型</uni-th>
						<uni-th align="center">是否必填</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center"> {{item.question_title}} </uni-td>
						<uni-td>
							<text>【</text>
							<text @click="addOption(item._id)" class="textbutton">新增选项</text>
							<text>】</text>
							<!-- <button @click="navigateTo('./add?parent_id=' + item._id + '&parent_name=' + item.name, false)" class="uni-button" size="mini" type="default">新增选项</button> -->
							<view v-for="(item_options,index_options) in item.children" :key="index_options">
								{{item_options.option_text}}
								<text>【</text>
								<text @click="updateOption(item_options._id,item_options.option_text)" class="textbutton">修改</text>
								<text>】</text>
								<text>【</text>
								<text @click="confirmDeleteOption(item_options._id)" class="textbutton">删除</text>
								<text>】</text>
								<!-- <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="default">修改</button>
						<button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button> -->
							</view>
						</uni-td>
						<uni-td align="center"> {{options.question_type_valuetotext[item.question_type]}} </uni-td>
						<uni-td align="center"> {{item.question_required}} </uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary">修改</button>
								<button @click="confirmDeleteQustion(item)" class="uni-button" size="mini" type="warn">删除</button>
								<button @click="navigateTo('./count?id='+item._id, false)" class="uni-button" size="mini" type="primary">查看统计</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<!-- <view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count"
					 @change="onPageChanged" />
				</view> -->
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter
	} from '@/js_sdk/validator/opendb-vote-question.js';

	const db = uniCloud.database()
	const dbCmd = db.command
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	export default {
		data() {
			return {
				questionnaire_id:'',
				query: '',
				startwith: '',
				orderby: dbOrderBy,
				options: {
					pageSize,
					pageCurrent,
					...enumConverter
				}
			}
		},
		onLoad(e) {
			const id = e.questionnaire_id
			if (id) {
				this.questionnaire_id = id
				this.startwith = "parent_id == '" + this.questionnaire_id + "'"
			}
			else {
				uni.showModal({
					content:"页面参数错误",
					showCancel:false
				})
			}
		},
		onReady() {
			if (this.questionnaire_id) {
				this.$refs.udb.loadData()
			}
		},
		methods: {
			search() {
				const newWhere = this.getWhere()
				const isSameWhere = newWhere === this.where
				this.where = newWhere
				if (isSameWhere) { // 相同条件时，手动强制刷新
					this.loadData()
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			//批量删除问题
			delTable() {
				this.$refs.udb.remove(this.selectedItems())
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			// 删除问题
			confirmDeleteQustion(objQustion) {
				var arrId = []
				arrId.push(objQustion._id)
				for (var i = 0; i < objQustion.children.length; i++) {
					arrId.push(objQustion.children[i]._id)
				}
				console.log("arrId: ", arrId);
				var that = this
				uni.showModal({
					content: "确认删除该问题以及问题下的所有选项？",
					success: function(res) {
						if (res.confirm) {
							uni.showLoading()
							db.collection("opendb-vote-question").where({_id: dbCmd.in(arrId)}).remove()
								.then((res) => {
									that.loadData() // 其实可以不联网刷，动态加数到界面上
									//console.log("删除成功，删除条数为: ",res.deleted);
								})
								.catch((err) => {
									console.log(err.message)
								})
								.finally(() => {
									uni.hideLoading()
								})
						}
					}
				})
			},
			// 新增选项
			addOption(parent_id) {
				var that = this
				// #ifndef H5
				// 暂不支持小程序
				return
				// #endif

				var option_text = prompt("输入选项内容")
				if (option_text != null && option_text != "" && parent_id != null && parent_id != "") {
					uni.showLoading()
					db.collection("opendb-vote-question").add({
							"option_text": option_text,
							"parent_id": parent_id
						})
						.then((res) => {
							that.loadData() // 其实可以不联网刷，动态加数到界面上
							//console.log("新建成功，新建条数为: ",res.deleted);
						})
						.catch((err) => {
							console.log(err.message)
						})
						.finally(() => {
							uni.hideLoading()
						})
				}
			},
			// 修改选项
			updateOption(option_id, old_text) {
				var that = this
				// #ifndef H5
				// 暂不支持小程序
				return
				// #endif
				var option_text = prompt("输入选项内容", old_text)
				if (option_text != null && option_text != "") {
					uni.showLoading()
					db.collection("opendb-vote-question").doc(option_id)
						.update({
							"option_text": option_text
						})
						.then((res) => {
							that.loadData() // 其实可以不联网刷，动态加数到界面上
							//console.log("修改成功，修改条数为: ",res.deleted);
						})
						.catch((err) => {
							console.log(err.message)
						})
						.finally(() => {
							uni.hideLoading()
						})
				}
			},
			// 删除选项
			confirmDeleteOption(optionid) {
				var that = this
				uni.showModal({
					content: "确认删除该选项？",
					success: function(res) {
						if (res.confirm) {
							uni.showLoading()
							db.collection("opendb-vote-question").doc(optionid).remove()
								.then((res) => {
									that.loadData() // 其实可以不联网刷，动态加数到界面上
									//console.log("删除成功，删除条数为: ",res.deleted);
								})
								.catch((err) => {
									console.log(err.message)
								})
								.finally(() => {
									uni.hideLoading()
								})
						}
					}
				})
			}
		}
	}
</script>
<style>
	.textbutton {
		font-size: 28rpx;
		text-decoration: underline;
		color: #3A8EE6;
		cursor: pointer;
	}
</style>
